package com.gimi.cloud.jimi.client.service.moreInfo.impl;

import com.gimi.cloud.jimi.client.service.moreInfo.SocialSecurityService;
import com.gimi.cloud.jimi.common.enums.ResponseCodeEnum;
import com.gimi.cloud.jimi.common.enums.common.RedisKeyEnum;
import com.gimi.cloud.jimi.common.exception.MsgException;
import com.gimi.cloud.jimi.common.mq.service.MqCommonSenderService;
import com.gimi.cloud.jimi.common.utils.DateUtil;
import com.gimi.cloud.jimi.common.utils.reqhead.Response;
import com.gimi.cloud.jimi.commonService.InterfacePlatform.impl.InterfaceUtil;
import com.gimi.cloud.jimi.common.mq.enume.QueueEnum;
import com.gimi.cloud.jimi.dao.dao.User.UserDao;
import com.gimi.cloud.jimi.dao.dao.moreInfo.MoreInfoDao;
import com.gimi.cloud.jimi.entity.app.moreInfo.MoreInfoEntity;
import com.gimi.cloud.jimi.entity.user.User;
import com.gimi.cloud.jimi.dto.params.SocialSecurityParam;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @auther loongs
 * @date 2018/1/11  11:32
 */
@Service
public class SocialSecurityServiceImpl implements SocialSecurityService {
    private final static String redisKey = RedisKeyEnum.JIMI_CONFIG_PRE.getKey() + "interface_platform_universal_socialSecurity";
    private final Integer MAXTIMES = 3;
    private MqCommonSenderService commonSenderService;
    private InterfaceUtil interfaceUtil;
    private MoreInfoDao moreInfoDao;
    private UserDao userDao;

    @Autowired
    public SocialSecurityServiceImpl(MqCommonSenderService commonSenderService, InterfaceUtil interfaceUtil, MoreInfoDao moreInfoDao, UserDao userDao) {
        this.commonSenderService = commonSenderService;
        this.interfaceUtil = interfaceUtil;
        this.moreInfoDao = moreInfoDao;
        this.userDao = userDao;
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRED)
    public Response getSheBaoLoginAndGrab(SocialSecurityParam socialSecurityParam) throws Exception {
        Response resp = new Response();
        User user = userDao.getUserByUserId(socialSecurityParam.getOperUserId());
        if (user == null) {
            throw new MsgException(ResponseCodeEnum.ERR_USER_INVALID);
        }
        //查询该用户之前是否有获取过社保信息
        MoreInfoEntity moreInfoEntity = moreInfoDao.getMoreInfoByUserIdAndType(socialSecurityParam.getOperUserId(),7);

        //半段是不是新增，true是新增，false已存在
        boolean flag = false;
        //返回值为2的时候，是代表时间已经过期
        if (moreInfoEntity != null && (DateUtil.compare(moreInfoEntity.getReportEffectionEnd(), DateUtil.getNow()) == 2 ||
                (DateUtil.compare(moreInfoEntity.getReportEffectionEnd(), DateUtil.getNow()) == 0 && !"2".equals(moreInfoEntity.getGetdata())))) {
            //如果是有效期内，就做修改，不做新增
            //如果是失败的且过期时间为空，就需要做修改，不做新增
        }else {
            //时间过期了的新增
            moreInfoEntity = new MoreInfoEntity();
            moreInfoEntity.setGetdataTime(new Date());
            moreInfoEntity.setAnalysis("0");

            //user相关
            moreInfoEntity.setAddTime(new Date());
            moreInfoEntity.setAddUname(user.getAddUname());
            moreInfoEntity.setAddUid(user.getUserId());
            moreInfoEntity.setUserId(user.getUserId());

            //1代表社保
            moreInfoEntity.setDataType("7");
            moreInfoEntity.setGetdataMaxTimes(MAXTIMES);

            flag = true;
        }

        //开始登录
        StringBuffer param = new StringBuffer();
        param.append("{");
        param.append("    \"head\":{");
        param.append("        \"apiname\":\"fengchaointerface\",");
        param.append("        \"serviceName\":\"fengchao_shebao_loginandgrab\"");
        param.append("    },");
        param.append("    \"body\":{");
        param.append("        \"op\":\"submitDynamicParams\",");
        param.append("        \"sessionToken\":\"#sessionToken#\",");
        param.append("        \"args\":\"#args#\"");
        param.append("    }");
        param.append("}");
        JSONObject object = JSONObject.fromObject(param.toString());
        object.getJSONObject("body").put("args", socialSecurityParam.getArgs());
        object.getJSONObject("body").put("sessionToken", socialSecurityParam.getSessionToken());
        socialSecurityParam.setInterfcaeParam(object.toString());
        socialSecurityParam.setRedisKey(redisKey);
        socialSecurityParam.setInterfcaeResultKey("check");
        interfaceUtil.call(socialSecurityParam);

        //状态接口去等待才能获取结果
        Thread.sleep(2 * 1000);

        socialSecurityParam.setInterfcaeParamKey("getgrabstatus");
        JSONObject resultObj = (JSONObject) interfaceUtil.call(socialSecurityParam);
        if (!"1".equals(resultObj.getString("status"))) {
            throw new MsgException(ResponseCodeEnum.INTERFACE_ERROR, resultObj.getString("errors"));
        }
        if ("LOGIN".equals(resultObj.getString("flowstate")) && "FAIL".equals(resultObj.getString("step"))) {
            throw new MsgException(ResponseCodeEnum.INTERFACE_ERROR, resultObj.getString("description"));
        }
        moreInfoEntity.setGetdata("1");
        if(flag){
            moreInfoDao.insertSelective(moreInfoEntity);
        }else{
            moreInfoEntity.setUpdateUid(user.getUserId());
            moreInfoEntity.setUpdateUname(user.getAddUname());
            moreInfoEntity.setUpdateTime(DateUtil.getNow());
            moreInfoDao.updateByPrimaryKey(moreInfoEntity);
        }

        resp.setResponseCode(ResponseCodeEnum.SUCCESSED);
        //通过队列获取报告
        commonSenderService.sendMessage2Rabbitmq(QueueEnum.FENGCHAO_SHEBAO_REPORT, socialSecurityParam);
        return resp;
    }
}
